package com.block.account.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.account.model.dto.ChangeAmountDTO;
import com.block.account.model.result.ChangeAmountResult;
import com.block.account.service.IAccountCommonService;
import com.block.account.service.IAccountMerchantInfoHisService;
import com.block.account.service.IAccountMerchantInfoService;
import com.block.db.entity.AccountMerchantInfo;
import com.block.db.mapper.AccountMerchantInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;

/**
 * <p>
 * 商户账户信息 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-08-26
 */
@Service
public class AccountMerchantInfoServiceImpl extends ServiceImpl<AccountMerchantInfoMapper, AccountMerchantInfo> implements IAccountMerchantInfoService, IAccountCommonService {

    @Autowired
    IAccountMerchantInfoHisService accountMerchantInfoHisService;

    @Override
    @Transactional
    public ChangeAmountResult changeAmount(ChangeAmountDTO changeAmountDTO) {

        AccountMerchantInfo accountMerchantInfo = this.baseMapper.getEntityByAccountIdLock(changeAmountDTO.getAccountId());
        // 修改账户余额
        BigDecimal totalAmount = NumberUtil.add(accountMerchantInfo.getZhiCoinAmount(), changeAmountDTO.getChangeZhiCoinAmount());

        ChangeAmountResult changeAmountResult = new ChangeAmountResult();
        changeAmountResult.setSuccess(false);
        changeAmountResult.setNoticeFlag(false);

        if (totalAmount.compareTo(BigDecimal.ZERO) < 0){
            changeAmountResult.setMessage("账户余额不足");
            return changeAmountResult;
        }

        /**
         * 修改金额
         */
        AccountMerchantInfo updateEntity = new AccountMerchantInfo();
        updateEntity.setAccountId(accountMerchantInfo.getAccountId());
        updateEntity.setZhiCoinAmount(totalAmount);
        boolean updateRes = this.updateById(updateEntity);
        if (!updateRes){
            return changeAmountResult;
        }

        boolean saveHis = accountMerchantInfoHisService.saveAccountHis(totalAmount, accountMerchantInfo, changeAmountDTO);
        if (!saveHis){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return changeAmountResult;
        }

        changeAmountResult.setSuccess(true);

        return changeAmountResult;
    }
}
